<template>
  <div class="page-content">
    <div class="header">
      <!-- 表格名称 -->
      <div class="header-title">{{ contentConfig.header?.title ?? '数据列表' }}</div>
      <!-- 表格上方操作按钮 -->
      <div class="header-actions">
        <!-- 统一新增按钮 -->
        <el-button type="primary" @click="handleAddNewClick" v-if="contentConfig.header?.btnTitle">
          {{ contentConfig.header?.btnTitle ?? '新增' }}
        </el-button>
        <!-- 统一批量删除按钮 -->
        <template v-if="contentConfig.hasTableSelection && !contentConfig.MultiBtn?.hideDelete">
          <!-- 批量删除 -->
          <el-button
            type="danger"
            :disabled="tableSelection.length === 0"
            @click="handleMultiDeleteClick"
            >批量删除</el-button
          >
        </template>
        <!-- 统一批量自定义按钮 -->
        <template v-if="contentConfig.MultiBtn">
          <el-button
            v-if="contentConfig.MultiBtn?.customName"
            type="success"
            @click="handleUserClick"
            >{{ contentConfig.MultiBtn?.customName }}</el-button
          >
        </template>
      </div>
    </div>

    <!-- 统一表格 -->
    <div class="table">
      <el-table
        v-loading="loading"
        :data="systemStore.pageDataList"
        style="width: 100%"
        border
        v-bind="contentConfig.childrenTree"
        @selection-change="handleTableSelectionChange"
      >
        <!-- 多选 -->
        <el-table-column
          v-if="contentConfig.hasTableSelection"
          :selectable="checkSelectable"
          type="selection"
          width="55"
          align="center"
        />
        <!-- 序号 -->
        <el-table-column
          v-if="contentConfig.hasTableIndex"
          type="index"
          width="55"
          label="序号"
          align="center"
        />
        <!-- 表格内容 -->
        <template v-for="item in contentConfig.tableItems" :key="item.prop">
          <el-table-column v-bind="item" :align="item.align ?? 'center'" show-overflow-tooltip>
            <template v-if="item.slotName" #default="scope">
              <slot :name="item.slotName" v-bind="scope" :prop="item.prop"></slot>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-if="systemStore.pageDataList?.length > 0 && Number(systemStore.pageDataTotalCount)"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="Number(systemStore.pageDataTotalCount)"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import useCommonStore from '@/stores/main/common/common'
import useSystemStore from '@/stores/main/system/system'
import { reactive, ref } from 'vue'
import { isCode } from '@/utils/iscode'
import type { IContentConfig } from './type'

// - props
const props = defineProps<{
  contentConfig: IContentConfig
}>()

// - store
const systemStore = useSystemStore()
const commonStore = useCommonStore()

// -data
const tableSelection = ref<any[]>([])
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})
const loading = ref<boolean>(false)

//批量封禁
// - emit
const emit = defineEmits(['addNewClick', 'editClick', 'userClick'])

// - methods

//多选选择
const handleTableSelectionChange = (val) => {
  tableSelection.value = val
}
//分页页数
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchPageData('page')
}
//分页页码
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchPageData('page')
}
//新增
const handleAddNewClick = () => {
  emit('addNewClick')
}

//自定义按钮
const handleUserClick = () => {
  emit('userClick')
}

//禁止某种状态被选择
const checkSelectable = (row: any) => {
  // if (props.contentConfig.pageName == 'usermanage/group') {
  //   return row.status !== 2
  // } else if (props.contentConfig.pageName == 'usermanage/user') {
  //   return row.status !== 4
  // } else {
  //   return row
  // }
  return row
}

//批量删除
const handleMultiDeleteClick = () => {
  loading.value = true
  let ids: any = []
  tableSelection.value.map((item: any) => {
    ids.push(item.id)
  })
  deleteDataById(ids)
}

// 统一查询数据
const fetchPageData = (type: string) => {
  loading.value = true
  if (Reflect.has(systemStore.searchData, 'date') && !systemStore.searchData.date) {
    systemStore.searchData.date = null
  }
  if (type == 'init') {
    pagination.currentPage = 1 // 重置当前页
  }
  const pageNumber = pagination.currentPage
  const pageSize = pagination.pageSize
  systemStore
    .fetchPageDataAction(
      props.contentConfig.pageName,
      {
        pageNumber,
        pageSize,
        ...systemStore.searchData
      },
      props.contentConfig.isMenu
    )
    .then(() => {
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

//统一删除
const deleteDataById = (payload: Array<number>) => {
  systemStore
    .deletePageDataAction(props.contentConfig.pageName + '/delete', payload)
    .then((res) => {
      if (isCode(res, true)) {
        // 更新页面数据
        fetchPageData('page')
      }
    })
}

//统一更改状态
const handleSwitchChange = (payload: any) => {
  systemStore
    .updateStatusAction(props.contentConfig.pageName + '/status', {
      id: payload.id,
      status: payload.status
    })
    .then((res: any) => {
      isCode(res)
    })
}

//更新角色
const updateCommonData = () => {
  commonStore.fetchEntireDataAction(1, 9999)
}

// - init fn
const init = () => {
  systemStore.resetState()
  if (!props.contentConfig.delay) {
    fetchPageData('init')
  }
}

init()
// - expose
defineExpose({
  fetchPageData,
  updateCommonData,
  pagination,
  deleteDataById,
  handleSwitchChange
})
</script>

<style lang="less" scoped>
.page-content {
  padding: 20px;
  margin-top: 20px;
  overflow: hidden;
  background-color: #fff;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-top: 10px;

    .header-title {
      font-size: 22px;
      font-weight: 800;
    }
  }

  .table {
    margin-top: 20px;

    :deep(.el-table) {
      .el-table__cell {
        padding: 10px 0;
      }
    }

    .action-btn {
      margin-left: 2px;
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    margin: 50px 0 30px 0;
  }
}
</style>
